package com.usian.day10.redis.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author baimugudu
 * @email 2415621370@qq.com
 * @date 2023/8/7 15:11
 */
@RestController
public class OrderController {

    @Autowired
    RedissonClient redissonClient;

    // 模拟DB数据
    private static final HashMap<String,Integer> db = new HashMap();
    static{
        db.put("1",10);
    }
    @GetMapping("/reset")
    public String reset(){
        db.put("1",10);
        return "重置库存成功";
    }

    /**
     * 分布式锁：key ：锁的标识
     *          value ：redisson 生成的值 UUID
     *           time ：ttl   30s    续期 当你的业务没有执行完，每过10s钟续期一次 20s  看门狗
     *           timeunit
     * @param username
     * @param goodsId
     * @return
     */
    @GetMapping("/createOrder")
    public String createOrder(String username,String goodsId){
        RLock lock = redissonClient.getLock(goodsId);
        lock.lock();
        try{
            System.out.println("username:"+username+"要进行下单操作...");
            Integer goods1 = db.get(goodsId);
            if(goods1!=null && goods1>0){
                try {
                    // 故意延迟100毫秒，为了更容易显现超卖情况
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 扣减库存
                db.put(goodsId,--goods1);

                System.out.println("username："+username+"下订单成功...剩余库存数量为："+goods1);
                return "username："+username+"下订单成功...剩余库存数量为："+goods1;
            }
            System.out.println("库存不足，下单失败");
            return "库存售罄，下单失败";
        }finally {
            lock.unlock();
        }

    }
}
